import router from '@/router';
import { appRoutes } from '@/router/addrouter';
import { reactive, computed } from 'vue';
import { userInFoPinia, useAppPinia } from '@pinia/pinia';
import { deepCopy } from '@/utils/baseMethods';
import { onMounted, ref } from 'vue';

export default function importConfig() {
  const base = reactive<any>({
    menuState: false,
    mRouter: null,
    powerList: [], // 用户权限
    selectedKeys: computed(() => {
      return router.currentRoute.value.name;
    }),
    openKeys: computed(() => {
      return router.currentRoute.value.meta.mapPath;
    }),
    appPinia: useAppPinia(),
    isInit: false,
  });

  const collapsed = computed({
    get() {
      if (base.appPinia.device === 'desktop') return base.appPinia.menuCollapse;
      return false;
    },
    set(value: boolean) {
      base.appPinia.updateSettings({ menuCollapse: value });
    },
  });

  /**
   *  路由权限判断逻辑,当路由中的show 为false的时候则直接放开权限通过
   *
   */
  const init = () => {
    // base.powerList = userPinia.userInFo.menuList;
    base.mRouter = handleRoute(appRoutes);
    // base.mRouter = appRoutes;
    mRouterDom();
  };

  // 路由限制
  const handleRoute = (appRoutes: any) => {
    const routers = deepCopy(appRoutes);
    const list: any = [];
    routers.map((item: any) => {
      const childList: any = [];
      item.children &&
        item.children.map((childItem: any) => {
          childList.push(childItem);
        });
      if (childList.length) {
        item.children = childList;
        list.push(item);
      }
    });
    return list;
  };

  /**
   * @exports collapseState 导航栏折叠状态判断
   */
  const collapseState = (param: any) => {
    /**
     * true :为折叠
     * flase:打开
     */
    base.menuState = param;
  };

  /**
   *@exports watchWidth 监听页面宽度变化,并改变样式
   */
  const watchWidth = () => {
    let timeOut: any; // 定义一个定时器
    window.onresize = () => {
      //屏幕尺寸变化
      if (!timeOut) {
        //是否存在定时器
        timeOut = setTimeout(() => {
          //创建一个定时器
          base.menuState = false;
          if (document.body.clientWidth <= 1200) {
            base.menuState = true;
          }
          timeOut = null;
        }, 500);
      }
    };
  };

  /**
   * @exports goto 菜单路由跳转操作
   */
  const goto = (param: any) => {
    router.push(param);
  };

  /**
   * @exports mRouterDom 标记当前路由全级,通过全级去发配菜单级数
   * @returns 返回false 意味着当前路由时空的
   */
  const mRouterDom = (): any => {
    if (base.mRouter == null) return false;
  };

  const setCollapsed = (val: boolean) => {
    // if (!base.isInit) return; // for page initialization menu state problem
    // base.appPinia.updateSettings({ menuCollapse: val });

    if (base.appPinia.device === 'desktop') base.appPinia.updateSettings({ menuCollapse: val });
  };

  onMounted(() => {
    base.isInit = true;
  });

  return {
    collapseState,
    base,
    collapsed,
    watchWidth,
    goto,
    init,
    setCollapsed,
  };
}
